package com.xiaohudie.aop;

import cn.hutool.core.bean.BeanUtil;
import com.xiaohudie.annotation.LogBiaoZhi;
import com.xiaohudie.pojo.MyLog;
import com.xiaohudie.pojo.User;
import com.xiaohudie.servier.MysqlLogServicer;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * @Author xiao hu die
 * @Date 2022/4/22 13:10
 * @Version 1.0
 */
@Component
@Aspect
@Slf4j
public class MysqlLogAspect {
    @Autowired
    private MysqlLogServicer mysqlLogServicer;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //获取当前登录用户的token  可以通过这个
    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    @Around("execution(* com.xiaohudie.controller.*.*(..)) && @annotation(logBiaoZhi)")
    public Object LogAspect(ProceedingJoinPoint proceedingJoinPoint, LogBiaoZhi logBiaoZhi) throws Throwable {
    log.info("开始记录日志进数据库了");
    MyLog myLog = new MyLog();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    myLog.setOperateTime(new Date());
        HttpServletRequest httpServletRequest = getHttpServletRequest();
        String token = httpServletRequest.getHeader("authorization");
    /*String token = request.getHeader("authorization");*/
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(token);
        User user = BeanUtil.fillBeanWithMap(userMap,new User(),false);
        myLog.setUserName(user.getName());
    /**获取类名*/
    myLog.setOperateClass(proceedingJoinPoint.getTarget().getClass().getName());
    /**获取方法名*/
    myLog.setOperateMethod(proceedingJoinPoint.getSignature().getName());
    /**获取参数名*/
    myLog.setOperateArgs(Arrays.toString(proceedingJoinPoint.getArgs()));
    long startTime = System.currentTimeMillis();
    /**执行方法*/
    Object proceed = proceedingJoinPoint.proceed();
    long endTime = System.currentTimeMillis();
    myLog.setCostTime(String.valueOf(endTime-startTime));
        System.out.println(myLog);
    mysqlLogServicer.InsertLog(myLog);
    log.info("日志记录完毕");
    return proceed;
}
}
